<?php

require_once 'Basic.php';

class SubsidiaryCreate extends BasicEntity {
  
  private static $actionName = "Create";
  
  private static $nameField = "name";
  private static $passwordField = 'password';
  
  public function __construct() {
    $this->fields = array(
        new FormField(true, SubsidiaryCreate::$nameField, "Nome", new FormFieldTextLine()),
        new FormField(true, SubsidiaryCreate::$passwordField, "Senha", new FormFieldPassword()),
    );
    $this->fields = Endereco::addAddress($this->fields);
    $this->processFields();
  }
  
  public function actionDescription() {
    return SubsidiaryCreate::$actionName;
  }
  
  public function actionCreate($userInput) {
    $name = $this->fields[SubsidiaryCreate::$nameField]->value();
    $password = $this->fields[SubsidiaryCreate::$passwordField]->value();
   
    $logradouro = $this->fields[Endereco::LOGRADOURO_FIELD]->value();
    $num = $this->fields[Endereco::NUMERO_FIELD]->value();
    $complemento = $this->fields[Endereco::COMPLEMENTO_FIELD]->value();
    $bairro = $this->fields[Endereco::BAIRRO_FIELD]->value();
    $cep = $this->fields[Endereco::CEP_FIELD]->value();
    $outrasInfo = $this->fields[Endereco::OUTRAS_INFO_FIELD]->value();
    $cidade = $this->fields[Endereco::CIDADE_FIELD]->value();
    $uf = $this->fields[Endereco::UF_FIELD]->value();
    
    if($num !== null) {
      $num = intval($num);
    }
    
    if($uf === "-"){
      $uf = null;
    }
        
    $db = new DBUtils();
    
    try {
      $db->connect();
      
      $db->runQuery("select idFilial from Filial where nome = ?", array($name));
      if($db->getItem() !== null) {
        $this->fields[SubsidiaryCreate::$nameField]->setValid(false);
        return "Filial com nome ${name} j&aacute; cadastrada.";
      }      
      
      $db->beginTransaction();
      
      $db->runQuery("insert into Endereco (bairro, numero, logradouro, CEP, complemento, outrasInformacoes, cidade, UF) values (?, ?, ?, ?, ?, ?, ?, ?)",
                    array($bairro, $num, $logradouro, $cep, $complemento, $outrasInfo, $cidade, $uf));
                    
      $db->runQuery("select ident_current('Endereco') as idEndereco");
      $idAddress = $db->getItem()->idEndereco;
      logMessage($idAddress);
      
      $db->runQuery("insert into Filial (nome, senha, endereco) values (?, ?, ?)",
              array($name, $password, $idAddress));  
              
      $db->close(true);
    }
    catch(DBError $e) {
      $db->close(false);
      logMessage($e->errors, "SubsidiaryCreate");
      return "Falha no banco de dados. O erro foi reportado.";
    }
    
    return true;
  }

}

mustBeAdmin();
correctStdFormGet();

$page = new Page("Cadastro de Filial");
$SubsidiaryCreate = new SubsidiaryCreate();
$form = new StdForm($SubsidiaryCreate, $_GET, $_POST,
        "<p>" . htmlentities("Campos em negrito são obrigatórios.") . "</p>",
        "<p>" . htmlentities("Cadastro realizado com sucesso. Agora você pode fazer logar no sistema.") . "</p>",
        "SubsidiaryCreate.php");
$form->processForm();
$page->addContent($form->getHtml());
echo $page->getHtml();